/**
 * 云数据库操作类
 */
import { cloud } from "@hw-agconnect/cloud-server";
import { Punch } from "../bean/Punch.js";
import dateHelper from "./date_helper.js";

/**
 * 云数据库存储区名称
 */
const ZONE_NAME = "PunchHelper01";

/**
 * 云数据库集合名称
 */
const collection = cloud.database({ zoneName: ZONE_NAME }).collection(Punch);

let testData = {
    code: 200,
    token: "adcsa",
    send_date: dateHelper.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
    punch: [
        {
            date: "2025-04-11",
            start_punch_date: "2025-04-11 08:30",
            photo_punch_date: "2025-04-11 10:30",
            end_punch_date: "2025-04-11 16:50"
        },
        {
            date: "2025-04-12",
            start_punch_date: "2025-04-12 08:30",
            photo_punch_date: "2025-04-12 10:30",
            end_punch_date: "2025-04-12 16:50"
        }
    ]
}

/**
 * 新增或更新Punch信息
 * @param {string} token 
 * @param {*} punch_data 
 * @returns 
 */
export async function upsertPunchData(token, punch_data) {
    try {
        const upsertNum = await collection.upsert([
            {
                token: token,
                punch_data: JSON.stringify(punch_data)
            }
        ]);

        console.log("upsertManInfos=>", upsertNum);
        console.info('DONE!')
        return Promise.resolve(0);
    } catch (err) {
        console.error(err);
        return Promise.reject(1);
    }
}

/**
 * 根据工号查询Punch信息
 * @param {string} token - 工号
 * @returns {Promise<Array>} - Punch对象数组
 */
export async function queryPunchRecordsByEmployeeId(token) {
    try {
        const punchInfos = await collection
            .query()
            .equalTo("token", token)
            .get();
        console.log("PunchInfos=>", punchInfos);
        return Promise.resolve(punchInfos);
    } catch (error) {
        console.error(error);
        return Promise.resolve([]);; // 返回空数组表示查询失败或无结果
    }
}

/**
 * 查询所有Punch信息
 * @returns {Promise<Array>} - Punch对象数组
 */
export async function listAllPunchInfos() {
    try {
        const punchInfos = await collection.query().get();
        console.log("PunchInfos=>", punchInfos);
        return Promise.resolve(punchInfos);
    } catch (error) {
        console.error(error);
        return Promise.resolve([]);; // 返回空数组表示查询失败或无结果
    }
}

// upsertPunchData("1", testData)
// queryPunchRecordsByEmployeeId("1")
// listAllPunchInfos()
